<?php

namespace app\api\validate;

use app\lib\exception\ParameterException;
use think\Validate;
use think\Request;

class BaseValidate extends Validate
{
    //封装check方法，获取异常
    public function goCheck()
    {
        //获取URL中所有数据
        //判断传入的参数是否存在
        $request = Request::instance();
        $param = $request->param();
        $result = $this->batch()->check($param);

        if (!$result) {
            $e = new ParameterException([
                'msg' => $this->error,
            ]);
            throw $e;
        } else {
            return true;
        }
    }

    //正整数验证规则
    protected function isNoEmpty($value, $rule = '', $data = '', $field = '')
    {
        if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) {
            return false;
        }
        return true;
    }

    //getDataByRule 从验证规则获取数据
    public function getDataByRule($arrays)
    {
        //@arrays   客户端传进来的所有参数
        //判断用户是否从body或headers传入了UID，不允许用户传入该字段    
        //不允许用户从客户端传进user_id、uid，防止被恶意覆盖
        //array_key_exists从数组中查找字段
        if (array_key_exists('user_id', $arrays) | array_key_exists('uid', $arrays)) {
            throw new ParameterException([
                'msg' => '参数中存在非法字段user_id or uid'
            ]);
        }

        //$newArray保存定义字段的值
        //循环验证器中$rule数组下的字段（$key）
        //把用户传进来与验证规则一致的字段保存到$newArray
        $newArray = [];
        foreach ($this->rule as $key => $value) {
            $newArray[$key] = $arrays[$key];
        }
        return $newArray;
    }
}
